package com.loongtech.bi.manager.system;

import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.support.Log;
import com.loongtech.core.jpa.manager.ManagerQueryCacheBase;
import com.loongtech.core.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.loongtech.bi.manager.system.SysProjectManager.projectIdNameMap;

@Service
public class BiServerManager extends ManagerQueryCacheBase<EntityBiServer> {
	private static final long serialVersionUID = 2L;
	
	@Autowired
	private SysUserManager		sysUserManager;
	
	public Map<String,String> getIdAndNameMap(int userId)
	{
		Map<String,String> map = new LinkedHashMap<String,String>();
		List<EntityBiServer> list = getByUserId(userId);
		//排序保证0在最前面
		Collections.sort(list, new Comparator<EntityBiServer>(){
			@Override
			public int compare(EntityBiServer o1, EntityBiServer o2)
			{
				return o1.getId().compareTo(o2.getId());
			}});
		for(EntityBiServer info: list)
		{
			map.put(info.getId(), info.getName());
		}
		return map;
	}
    
    public List<EntityBiServer> getByUserId(int userId)
    {
		// 对超级用户特殊处理
		if (sysUserManager.isAdmin(userId))
		{
			return super.findAll();
		}
    			
    	//根据授权处理
    	List<EntityBiServer> list = new ArrayList<>();
    	Set<String> set = new HashSet<>();
    	List<Object> oList = findByQuery("select ss from EntitySysUserRole as ur, EntitySysRoleServer as rs, EntityServer as ss where ur.roleId = rs.roleId and rs.serverId = ss.id and ur.userId =:userId","userId",userId);
    	if (null != oList && !oList.isEmpty())
    	{
    		for (Object o : oList)
    		{
    			EntityBiServer server = (EntityBiServer) o;
    			if (set.add(server.getId()))
    			{
    				list.add(server);
    			}
    		}
    	}
    	return list;
    }
	
	/**
	 * 更新或者插入记录
	 * 
	 * @param server
	 * @return EntityBiServer the newOne
	 */
	public EntityBiServer insertOrUpdate(EntityBiServer server) {
		if (null == server || null == server.getId() || null == server.getName()) {
			Log.bi.error("BiServerManager insertOrUpdate param error !");
			return null;
		}

		// 新增
		EntityBiServer cur = get(server.getId());
		if (null == cur) {
			persist(server);
			flush();
			return server;
		}

		// 修改
		boolean hasChanged = false;
		String name = cur.getName();
		String desc = cur.getDescription();
		// 判断名称是否修改
		if (null != name && !name.equals(server.getName())) {
			hasChanged = true;
			cur.setName(server.getName());
		}

		// 判断描述是否修改
		if (null != desc && !desc.equals(server.getDescription())) {
			hasChanged = true;
			cur.setDescription(server.getDescription());
		}

		// 如果修改就保存入库
		if (hasChanged) {
			merge(cur);
			flush();
		}
		return cur;
	}

    /**
     * 查询任务(springmvc)
     */
    public Page<List<EntityBiServer>> queryByCriteria(Integer curPage, Integer pageSize, EntityBiServer entity) {
        List<Object> cons = new ArrayList<>();
        StringBuilder hql = new StringBuilder(" from EntityBiServer e where 1=1 ");
        if (!Utils.isEmptyStr(entity.getId())) {
            hql.append(" and e.id = ? ");
            cons.add(entity.getId());
        }
        if (!Utils.isEmptyStr(entity.getName())) {
            hql.append(" and e.name like ?");
            cons.add("%" + entity.getName() + "%");
        }
        if (entity.getGameId() != null) {
            hql.append(" and e.gameId = ?");
            cons.add(entity.getGameId());
        }
        if (!Utils.isEmptyStr(entity.getDescription())) {
            hql.append(" and e.description like ?");
            cons.add("%" + entity.getDescription() + "%");
        }
        if (!Utils.isEmptyStr(entity.getServerType())) {
            hql.append(" and e.serverType like ?");
            cons.add("%" + entity.getServerType() + "%");
        }
        hql.append(" order by e.gameId,e.id");
        Integer totalSize = countNum(hql.toString(), cons.toArray());
        //数据
        List<EntityBiServer> list = findByQuery((curPage - 1) * pageSize, pageSize, hql.toString(), cons.toArray());
        List<EntityBiChannel> clist = BiPlatformManager.CHANNEL_LIST;
        Map<String, String> map = new HashMap<>();
        if(clist != null && clist.size() > 0) {
            for (EntityBiChannel entityBiChannel : clist) {
                map.put(entityBiChannel.getId(), entityBiChannel.getName());
            }
        }
        if (list != null && list.size() > 0) {
            for (EntityBiServer entityBiServer : list) {
                List<String> res = entityBiServer.getChannelIdList();
                if (res != null && res.size() > 0) {
                    for (String s : res) {
                        entityBiServer.getChannelNameList().add(map.get(s));
                    }
                }
                entityBiServer.setGameName(projectIdNameMap.get(entityBiServer.getGameId().toString()));
            }
        }
        return new Page<>(list, totalSize, curPage, pageSize);
    }
}
